<?
 //生成二维码
$data=$_POST['openid'];
$ass=getAccessToken();
//判断是否存在
$rowqr=mysql_query("SELECT * FROM `qrcode` where openid = '$data' ");
$rowbool=$back=mysql_fetch_assoc($row);
if(empty($rowbool)){
$base_img = getminicode($ass,$data);
$qr='https://www.blgza.com/formal/'.'share/'.base64_image_content($base_img);
$appid = $_POST['appid'] ;
$secret = $_POST['secret'];
//
//写入数据库
 $newsql=mysql_query("INSERT INTO `qrcode`(qrcode,openid) VALUES ('$qr','$data')"); 
  mysql_close();  
echo($newsql);
}else{
    return $rowbool['qrcode'];
}
 //function
 
 //
 function getminicode($token,$id){
    $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$token;
    $data = array(
        "page"=>"pages/qrcode/qrcode",
        "scene"=>$id,
        "width"=>280,
        );
    $res = request_post($url,$data);
    return $res;
}
 // 获取微信服务器token
function getAccessToken()
{
  $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid .'&secret='.$secret;
  $res = json_decode(file_get_contents($url),true);
  $token = $res['access_token'];
  return $token;
}


// post请求模板
function request_post($url, $array)
{
    $postdata =  json_encode($array);
  $opts = array('http' =>
  array(
    'method' => 'POST',
    'header' => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata
  ));
  $context = stream_context_create($opts);
  $result = file_get_contents($url, false, $context);
  return $result;
}



function base64_image_content($base64_image_content){
   $imgDir = './share/';   //必须是项目所在的绝对路径
        //要生成的图片名字
        $filename =md5(time().mt_rand(10, 9999999)).".png"; //新图片名称
        $newFilePath = $imgDir.$filename;

    $data = $base64_image_content;
    $newFile = fopen($newFilePath,"w");
    fwrite($newFile,$data);
    fclose($newFile);
    return $filename;
}
//
?>